package com.tuvi.nhamthin.activity;

import java.text.Format.Field;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.tuvi.nhamthin.R;
import com.tuvi.nhamthin.dialog.ChonGoiTinh;
import com.tuvi.nhamthin.entity.GiapItem;
import com.tuvi.nhamthin.helper.SqlHelper;
import com.tuvi.nhamthin.services.BackgroundMusic;

public class Giap extends BaseActivity implements OnClickListener,
OnItemClickListener {
	private GiapAdapter adap;
	private ListView giapList;
	/** Button Back */
	private ImageButton mBtnBack;
	/** Called when the activity is first created. */

	private SqlHelper dbHelper = null;
	private Cursor currentCursor = null;
	private ArrayList<GiapItem> mGiapItems;
	private int tuoi;
	private String name = null;
	private String parent = null;
	private String fullName = null;
	private View giap;
	@Override
	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.giap);
		Intent intent = getIntent();
		tuoi = intent.getIntExtra("tuoi", -1);
		name = intent.getStringExtra("name");
		parent = intent.getStringExtra("parent");
		fullName = intent.getStringExtra("full_name");
		TextView title = (TextView)findViewById(R.id.title);
		
		if (fullName == null) {
			fullName = getTitle(tuoi);
			loadBackground(tuoi);
		}else{
			loadBackground("giap_" + parent.toLowerCase());
		}
		title.setText(fullName);
		giapList = (ListView) findViewById(R.id.giap_lst);

		if (this.dbHelper == null) {
			this.dbHelper = new SqlHelper(this);
		}
		new LoadDataTask().execute();
		giapList.setCacheColorHint(0);
		giapList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mBtnBack = (ImageButton) findViewById(R.id.btn_back);
		mBtnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// your code here
				finish();
			}
		});
		mGiapItems = new ArrayList<GiapItem>();
		giapList.setOnItemClickListener(this);
	}
	private void loadBackground(int tuoi){
		String nam ="Ty";
		switch (tuoi) {
		case 1:
			nam ="Ty";
			break;
		case 2:
			nam ="Suu";
			break;
		case 3:
			nam ="Dan";
			break;
		case 4:
			nam ="Mao";
			break;
		case 5:
			nam ="Thin";
			break;
		case 6:
			nam ="Tyj";
			break;
		case 7:
			nam ="Ngo";
			break;
		case 8:
			nam ="Mui";
			break;
		case 9:
			nam ="Than";
			break;
		case 10:
			nam ="Dau";
			break;
		case 11:
			nam ="Tuat";
			break;
		case 12:
			nam = "Hoi";
			break;
		default:
			break;
		}
		String name = "giap_"+nam;
		loadBackground(name);
	}
	private void loadBackground(String name){
		LinearLayout v = (LinearLayout)findViewById(R.id.giap);
		try {
			/*Class res = R.drawable.class;
		    java.lang.reflect.Field field = res.getField(name);
		    int drawableId = field.getInt(null);
			 */
			Resources r = getResources();
			String name1 = name.toLowerCase();
			int drawableId = r.getIdentifier(name1, "drawable", "com.tuvi.nhamthin");
			v.setBackgroundResource(drawableId);
		}
		catch (Exception e) {
			Log.e("MyTag", "Failure to get drawable id.", e);
		}
	}
	private String getTitle(int tuoi){
		String nam ="Tý";
		switch (tuoi) {
		case 1:
			nam ="Tý";
			break;
		case 2:
			nam ="Sửu";
			break;
		case 3:
			nam ="Dần";
			break;
		case 4:
			nam ="Mão";
			break;
		case 5:
			nam ="Thìn";
			break;
		case 6:
			nam ="Tỵ";
			break;
		case 7:
			nam ="Ngọ";
			break;
		case 8:
			nam ="Mùi";
			break;
		case 9:
			nam ="Thân";
			break;
		case 10:
			nam ="Dậu";
			break;
		case 11:
			nam ="Tuất";
			break;
		case 12:
			nam = "Hợi";
			break;
		default:
			break;
		}
		return "Tuổi " + nam;
	}
	@Override
	public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
		// TODO Auto-generated method stub
		ChonGoiTinh mChonGioiTinh = new ChonGoiTinh(this, null);
		mChonGioiTinh.show();
		mChonGioiTinh.getWindow().setBackgroundDrawable(new ColorDrawable(0));
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

	private class LoadDataTask extends AsyncTask<String, Void, String> {

		protected void onPreExecute() {
			// this.dialog.setMessage("Getting Names...");
			// this.dialog.show();
		}

		protected String doInBackground(final String... args) {
			try {
				Giap.this.dbHelper.createDatabase();
				Giap.this.dbHelper.openDataBase();
				// Giap.this.currentCursor = Giap.this.dbHelper.getCursor();
				//Route from Main Screen
				if (Giap.this.tuoi >0) {
					Giap.this.currentCursor = Giap.this.dbHelper.getRawCursor(Giap.this.tuoi);
				}else{
					//Route from search by age in about
					if (Giap.this.parent != null) {
						Giap.this.currentCursor = Giap.this.dbHelper.getRawCursor(Giap.this.parent);
					}
				}
			} catch (SQLException sqle) {
				throw sqle;
			}
			return null;
		}

		// can use UI thread here
		protected void onPostExecute(final String result) {
			startManagingCursor(Giap.this.currentCursor);
			while (Giap.this.currentCursor.moveToNext()) {
				GiapItem item = new GiapItem(
						Giap.this.currentCursor.getString(Giap.this.currentCursor
								.getColumnIndex(SqlHelper.COLUMN_NAME)),
								Giap.this.currentCursor.getString(Giap.this.currentCursor
										.getColumnIndex(SqlHelper.COLUMN_FULLNAME)),
										Giap.this.currentCursor.getString(Giap.this.currentCursor
												.getColumnIndex(SqlHelper.COLUMN_DESCRIPTION)),
												null,
												null,
												null,
												null,
												null,
												null,
												Giap.this.currentCursor.getString(Giap.this.currentCursor
														.getColumnIndex(SqlHelper.COLUMN_IMAGE_ICON)));
				Giap.this.mGiapItems.add(item);
			}
			//Giap.this.currentCursor.close();

			Giap.this.adap = new GiapAdapter(Giap.this, Giap.this.dbHelper,
					Giap.this.currentCursor, Giap.this.mGiapItems, Giap.this.name);
			Giap.this.giapList.setAdapter(Giap.this.adap);
			int selected = Giap.this.adap.getSelectedPos();
			if (selected >=0) {
				Giap.this.giapList.setSelection(selected);
			}
		}
	}

	public static class GiapAdapter extends BaseAdapter implements Filterable {
		private LayoutInflater mInflater;
		private Context context;
		private SqlHelper dbHelper;
		private Cursor currentCursor;
		private ArrayList<GiapItem> mGiapItems;
		private String name;
		private int selectedPos = -1;

		public GiapAdapter(Context context, SqlHelper dbHelper,
				Cursor currentCursor, ArrayList<GiapItem> mGiapItems, String name) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			this.context = context;
			this.dbHelper = dbHelper;
			this.currentCursor = currentCursor;
			this.mGiapItems = mGiapItems;
			this.name = name;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;

			//this.currentCursor.moveToPosition(position);
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.giap_item, null);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.detail = (TextView) convertView
				.findViewById(R.id.detail);
				convertView.setOnClickListener(new OnClickListener() {
					private int pos = position;

					@Override
					public void onClick(View v) {
						GiapItem item = (GiapItem)getItem(position);
						ChonGoiTinh mChonGioiTinh = new ChonGoiTinh(context, item.getName());
						mChonGioiTinh.show();
						mChonGioiTinh.getWindow().setBackgroundDrawable(new ColorDrawable(0));
					}
				});
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			GiapItem item = this.mGiapItems.get(position);
			holder.title.setText(item.getFullName());
			holder.detail.setText(item.getDescription());
			if (this.name != null) {
				if (name == item.getName()) {
					this.selectedPos = position;
				}
			}
			return convertView;
		}

		static class ViewHolder {
			TextView title;
			TextView detail;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.mGiapItems.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return this.mGiapItems.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

		public void setSelectedPos(int selectedPos) {
			this.selectedPos = selectedPos;
		}

		public int getSelectedPos() {
			return selectedPos;
		}

	}

	@Override
	public void onStop() {
		super.onStop();
		try {
			this.currentCursor.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
	}
	public void openDetail(String htmlName){
		Intent i = new Intent(this, AgeDetail.class);
		i.putExtra("htmlName", htmlName);
		this.startActivity(i);

	}
	public void openActive(String name, int gender){
		Intent i = new Intent(this, Active.class);
		i.putExtra("name", name);
		i.putExtra("gender", gender);
		this.startActivity(i);
	}
}
